<template>
  <div class="iChat">
    <!-- 顶部显示房间号和修改人数上限按钮 -->
    <div class="room-info">
      <span>房间号：{{ roomId }}</span>
      <button v-if="isOwner" @click="showMaxUsersDialog = true">修改人数上限</button>
    </div>

    <!-- 主容器flex布局，左侧聊天区，右侧用户列表 -->
    <div class="main-container">
      <!-- 聊天聊天内容区域 -->
      <div class="container">
        <div class="content">
          <div class="item item-center"><span>{{ formatRealTime() }}</span></div>
          <div class="item" v-for="(item, index) in receivedMessage" :key="index" :class="{'item-right':isCurrentUser(item),'item-left':!isCurrentUser(item)}">
            <!-- 右结构 -->
            <div v-if="isCurrentUser(item)" style="display: flex">
              <div class="bubble" :class="{'bubble-right':isCurrentUser(item),'bubble-left':!isCurrentUser(item)}">{{item.message}}</div>
              <div class="avatar">
                <img :src="getUserAvatar(item.userId)"/>
                {{item.userId}}
              </div>
            </div>
            <!-- 左结构 -->
            <div v-else style="display: flex">
              <div class="avatar">
                {{item.userId}}
                <img :src="getUserAvatar(item.userId)"/>
              </div>
              <div class="bubble" :class="{'bubble-right':isCurrentUser(item),'bubble-left':!isCurrentUser(item)}">{{item.message}}</div>
            </div>
          </div>
        </div>
        <div class="input-area">
          <textarea v-model="message" id="textarea" placeholder="输入消息..."></textarea>
          <div class="button-area">
            <button id="send-btn" @click="sendMessage()">发 送</button>
          </div>
        </div>
      </div>

      <!-- 右侧在线用户列表 -->
      <div class="user-list">
        <h4>在线用户 ({{ roomUsers.length }})</h4>
        <button v-if="isOwner" @click="openChangeOwnerDialog" class="change-owner-btn">
          移交房主
        </button>
        <ul>
          <li v-for="user in roomUsers" :key="user">
            <span>{{ user }} {{ user === roomOwner ? '(房主)' : '' }}</span>
            <!-- 房主可见踢人按钮，且不能踢自己 -->
            <button
                v-if="isOwner && user !== userId"
                @click="kickUser(user)"
                class="kick-btn"
            >
              踢出
            </button>
          </li>
        </ul>
      </div>
    </div>

    <!-- 修改人数上限弹窗（仅房主可见） -->
    <div v-if="showMaxUsersDialog" class="dialog-mask">
      <div class="dialog">
        <h3>修改房间人数上限</h3>
        <input
            type="number"
            v-model="newMaxUsers"
            min="1"
            placeholder="输入新的人数上限"
        >
        <div class="dialog-btns">
          <button @click="showMaxUsersDialog = false">取消</button>
          <button @click="setRoomMaxUsers">确认</button>
        </div>
      </div>
    </div>

    <!-- 移交房主弹窗（仅房主可见） -->
    <div v-if="showChangeOwnerDialog" class="dialog-mask">
      <div class="dialog">
        <h3>移交房主权限</h3>
        <select v-model="targetOwnerId" class="select-user">
          <option value="">选择接收权限的用户</option>
          <option v-for="user in roomUsers" :key="user" :value="user" v-if="user !== userId">
            {{ user }}
          </option>
        </select>
        <div class="dialog-btns">
          <button @click="showChangeOwnerDialog = false">取消</button>
          <button @click="changeRoomOwner" :disabled="!targetOwnerId">确认移交</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { jwtDecode } from "jwt-decode";
import axios from "axios";

export default {
  data() {
    return {
      ws: null,
      message: '',
      receivedMessage: [],
      userId: null,
      roomId: null,
      username: null,
      // 房主相关状态
      isOwner: false, // 是否为房主
      roomOwner: '', // 房间房主ID
      roomUsers: [], // 在线用户列表
      newMaxUsers: 10, // 新人数上限
      showMaxUsersDialog: false, // 修改上限弹窗开关
      avatarCache: {},//头像地址
      defaultAvatar: "https://picsum.photos/42/42",//默认头像地址
      // 新增：移交房主相关
      showChangeOwnerDialog: false, // 移交房主弹窗开关
      targetOwnerId: '' // 目标房主ID

    };
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    getUserAvatar(userId) {
      // 1. 先查缓存，有则直接返回
      console.log(userId)
      if (this.avatarCache[userId] !== undefined) {
        return this.avatarCache[userId];
      }

      // 2. 无缓存则请求后端接口
      // 注意：后端接口参数是Integer类型，这里确保userId转为数字
      const userIdNum = Number(userId);
      const token = sessionStorage.getItem("token");
      axios.get(`http://localhost:8080/user/avatar/${userIdNum}`,{
        headers: {
          "token": token // 添加token到请求头
        }
      })
          .then(response => {
            // 后端返回的ResponseUtil结构：{ code, data, msg }
            if (response.data.code === 200) { // 假设ResponseEnum.OK的code是200
              const fullAvatarUrl = response.data.data.avatar;
              this.avatarCache[userId] = fullAvatarUrl;
            } else {
              // 接口返回失败（如用户不存在），使用默认头像
              this.avatarCache[userId] = this.defaultAvatar;
            }
          })
          .catch(error => {
            // 网络错误等异常情况，使用默认头像
            console.error(`获取用户${userId}头像失败`, error);
            this.avatarCache[userId] = this.defaultAvatar;
          });

      // 3. 先返回默认头像，接口请求完成后会自动更新为真实头像
      return this.defaultAvatar;
    },
    handleHistoryMessages(historyData) {
      if (historyData.messages && historyData.messages.length > 0) {
        console.log(`加载 ${historyData.messages.length} 条历史消息`);
        // 将每条历史消息加入接收列表
        historyData.messages.forEach(msg => {
          if (msg.message && msg.userId) {
            this.receivedMessage.push(msg);
          }
        });
        // 滚动到最新消息
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    }
  ,
    formatRealTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const isToday = now.toDateString() === new Date().toDateString();
      if (isToday) {
        return `${hours}:${minutes}`;
      } else {
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      }
    },

    initWebSocket() {
      // 获取token
      const token = sessionStorage.getItem("token");
      if (!token) {
        console.error("未登录，无法建立WebSocket连接");
        this.$router.push('/login'); // 未登录则跳转到登录页
        return;
      }

      // 从token解析用户ID
      this.userId = this.parseUserIdFromToken(token);
      this.roomId = 11; // 可以根据实际需求修改房间ID获取方式

      // 建立WebSocket连接
      this.ws = new WebSocket(`ws://localhost:8080/chatWebSocket/${this.roomId}/${this.userId}`);

      this.ws.onopen = function() {
        console.log("websocket已打开");
      };

      // 消息处理
      this.ws.onmessage = (event) => {
        let messageData;
        try {
          messageData = JSON.parse(event.data);

          if (messageData.type === "system") {
            // 系统消息处理
            if (messageData.message) {
              alert(messageData.message);
            }
            // 更新是否为房主
            if (messageData.isOwner !== undefined) {
              this.isOwner = messageData.isOwner;
              this.roomOwner = messageData.roomOwner || '';
            }
            // 更新用户列表
            if (messageData.userList) {
              this.roomUsers = messageData.userList;
            }
          } else if (messageData.type === "error") {
            alert(messageData.message);
          }else if (messageData.type === "history") {
            // 新增：处理历史消息
            this.handleHistoryMessages(messageData);
          } else {
            // 聊天消息正常显示
            this.receivedMessage.push(messageData);
          }
        } catch (e) {
          // 兼容旧格式
          messageData = {
            userId: "system",
            message: event.data,
            roomId: this.roomId
          };
          if (messageData.message) {
            this.receivedMessage.push(messageData);
          }
        }
        // 滚动到底部
        this.scrollToBottom();
      };

      this.ws.onclose = function() {
        console.log("websocket已关闭");
        alert("与服务器连接已断开");
      };

      this.ws.onerror = function(error) {
        console.log("websocket发生错误:", error);
        alert("连接出错，请刷新页面重试");
      };
    },

    // 发送消息
    sendMessage() {
      if (!this.message.trim()) return;

      const sendData = {
        message: this.message,
        type: "chat" // 标记为聊天消息
      };

      this.ws.send(JSON.stringify(sendData));

      // 自己的消息立即显示
      this.receivedMessage.push({
        userId: this.userId,
        message: this.message,
        roomId: this.roomId,
        type: "chat"
      });

      this.message = '';
      this.scrollToBottom();
    },

    // 踢人功能
    kickUser(targetUserId) {
      if (confirm(`确定踢出用户${targetUserId}吗？`)) {
        this.ws.send(JSON.stringify({
          type: "kick",
          targetUserId: targetUserId
        }));
      }
    },

    // 修改人数上限
    setRoomMaxUsers() {
      if (this.newMaxUsers < 1) {
        alert("人数上限不能小于1");
        return;
      }
      this.ws.send(JSON.stringify({
        type: "setMaxUsers",
        maxUsers: this.newMaxUsers
      }));
      this.showMaxUsersDialog = false;
    },

    // 打开移交房主弹窗
    openChangeOwnerDialog() {
      this.targetOwnerId = '';
      this.showChangeOwnerDialog = true;
    },

    // 提交移交房主请求
    changeRoomOwner() {
      if (!this.targetOwnerId) return;

      this.ws.send(JSON.stringify({
        type: "changeOwner",
        targetUserId: this.targetOwnerId
      }));
      this.showChangeOwnerDialog = false;
    },

    // 判断是否为当前用户的消息
    isCurrentUser(item) {
      return item.userId == this.userId;
    },

    // 从token解析用户ID
    parseUserIdFromToken(token) {
      try {
        const decoded = jwtDecode(token);
        console.log("解析后的token payload：", decoded);
        // 确保提取的字段与token中实际的用户ID字段一致
        const userId = decoded.userId || decoded.id || decoded.user_id;
        if (!userId) {
          console.error("token中未找到用户ID字段");
          return null;
        }
        return userId.toString(); // 转为字符串，避免数字类型问题
      } catch (error) {
        console.error("解析token失败：", error);
        return null;
      }
    },

    // 滚动到最新消息
    scrollToBottom() {
      this.$nextTick(() => {
        const content = document.querySelector('.content');
        if (content) {
          content.scrollTop = content.scrollHeight;
        }
      });
    }
  },
  //历史消息

  beforeDestroy() {
    // 关闭WebSocket连接
    if (this.ws) {
      this.ws.close();
    }
  }
};
</script>

<style lang="scss" scoped>
// 顶部房间信息样式
.room-info {
  padding: 10px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-weight: bold;
    color: #333;
  }

  button {
    padding: 5px 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #359e6d;
    }
  }
}

// 主容器flex布局（左侧聊天，右侧用户列表）
.main-container {
  display: flex;
  width: 100%;
  height: calc(100vh - 60px);

  .container {
    flex: 1; // 聊天区占大部分宽度
    height: 100%;
  }
}

// 右侧用户列表样式
.user-list {
  width: 260px;
  border-left: 1px solid #e0e0e0;
  padding: 10px;
  background-color: #fff;
  overflow-y: auto;

  h4 {
    margin: 0 0 10px 0;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
  }

  ul {
    list-style: none;
    padding: 0;
  }

  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f5f5f5;
  }

  .kick-btn {
    padding: 2px 8px;
    font-size: 12px;
    background-color: #ff4d4f;
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #d93025;
    }
  }

  .change-owner-btn {
    width: 100%;
    padding: 6px;
    margin-bottom: 15px;
    background-color: #2f54eb;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #1d4ed8;
    }
  }
}

// 弹窗样式
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .dialog {
    width: 320px;
    background-color: white;
    padding: 20px;
    border-radius: 6px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0 0 15px 0;
      text-align: center;
      color: #333;
    }

    input, .select-user {
      width: 100%;
      padding: 8px 10px;
      margin-bottom: 15px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;

      &:focus {
        outline: none;
        border-color: #42b983;
        box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
      }
    }

    .dialog-btns {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;

      button {
        padding: 6px 18px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
      }

      button:first-child {
        background-color: #eee;
        color: #666;

        &:hover {
          background-color: #e0e0e0;
        }
      }

      button:last-child {
        background-color: #42b983;
        color: white;

        &:hover {
          background-color: #359e6d;
        }

        &:disabled {
          background-color: #ccc;
          cursor: not-allowed;
        }
      }
    }
  }
}

// 聊天容器样式
.container {
  height: 100%;
  border-radius: 4px;
  border: 0.5px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  flex-flow: column;
  overflow: hidden;
}

.content {
  width: calc(100% - 40px);
  padding: 20px;
  overflow-y: scroll;
  flex: 1;
}

.content:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
}

.bubble {
  max-width: 400px;
  padding: 10px;
  border-radius: 10px;
  position: relative;
  color: #000;
  word-wrap: break-word;
  word-break: normal;
}

.item-left .bubble {
  margin-left: 15px;
  background-color: #fff;
}

.item-left .bubble:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-top: 10px solid transparent;
  border-right: 10px solid #fff;
  border-bottom: 10px solid transparent;
  left: -20px;
}

.item-right .bubble {
  margin-right: 15px;
  background-color: #9eea6a;
}

.item-right .bubble:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid #9eea6a;
  border-top: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  right: -20px;
}

.item {
  margin-top: 15px;
  display: flex;
  width: 100%;
}

.item.item-right {
  justify-content: flex-end;
}

.item.item-center {
  justify-content: center;
}

.item.item-center span {
  font-size: 12px;
  padding: 2px 4px;
  color: #fff;
  background-color: #dadada;
  border-radius: 3px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
}

.avatar img {
  width: 42px;
  height: 42px;
  border-radius: 50%;
}

.avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.input-area {
  border-top: 0.5px solid #e0e0e0;
  height: 150px;
  display: flex;
  flex-flow: column;
  background-color: #fff;
}

textarea {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  overflow-y: auto;
  overflow-x: hidden;
  outline: none;
  resize: none;
}

.button-area {
  display: flex;
  height: 40px;
  margin-right: 10px;
  line-height: 40px;
  padding: 5px;
  justify-content: flex-end;
}

.button-area button {
  width: 80px;
  border: none;
  outline: none;
  border-radius: 4px;
  float: right;
  cursor: pointer;
  background-color: #42b983;
  color: white;
  transition: background-color 0.2s;

  &:hover {
    background-color: #359e6d;
  }

  &:active {
    background-color: #2d8c5c;
  }
}

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  border-radius: 8px;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0);
}

.content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
}
</style>
